<?php

namespace app\admin\controller\information;

use app\admin\library\Auth;
use app\common\controller\Backend;
use fast\Tree;
use think\Exception;
use think\model\relation\HasOne;
use think\Db;
use app\admin\model\information\InventoryClass;
use app\admin\model\information\KisBaseinfo;
/**
 * 货架管理管理
 *
 * @icon fa fa-circle-o
 */
class Shelves extends Backend
{

    /**
     * Shelves模型对象
     * @var \app\admin\model\information\Shelves
     */
    protected $model = null;
    protected $kcModel = null;
    protected $searchFields = 'number,name,remark';
    protected $radioArr = [1=>'是','否'];
    protected $whTypeArr = [1=>'标准仓','代管仓'];
    protected $noNeedLogin = ['indexpad','indexpad2'];
    
    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\information\Shelves;
        $this->kcModel = new \app\admin\model\inventory\Wmskc;
        
        $this->view->assign("typeList", $this->model->getTypeList());
        $this->view->assign("ifemptyList", $this->model->getIfemptyList());
        $this->view->assign("switchList", $this->model->getSwitchList());
        $this->view->assign("sourceList", $this->model->getSourceList());
        $this->view->assign("radioArr", $this->radioArr);
        $this->view->assign("whTypeArr", $this->whTypeArr);
        //$this->view->assign("warehouseArr", KisBaseinfo::getStock());
        $warehouseArr = db('warehouse')->where('switch',1)
                        ->field('id fItemId,name fName')
                        ->select();
        $this->view->assign("warehouseArr", $warehouseArr);

        $this->view->assign('erp_account_arr',config('site.acctNumberArr'));
        $this->view->assign('erp_stock_arr',config('site.erpStockArr'));
    }

    /**
     * 查看
     *
     * @return string|Json
     * @throws \think\Exception
     * @throws DbException
     */
    public function indexpad2()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if (false === $this->request->isAjax()) {
            return $this->view->fetch();
        }
    }

    /**
     * 查看
     *
     * @return string|Json
     * @throws \think\Exception
     * @throws DbException
     */
    public function indexpad()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if (false === $this->request->isAjax()) {
            return $this->view->fetch();
        }

        $op = $this->request->get("op", '', 'trim');
        $op = (array)json_decode($op, true);
        $filter = $this->request->get("filter", '');
        $where2 = [];
        if($filter){
            $filter=urldecode($filter);
            $filter=json_decode($filter,TRUE);
            if(isset($filter['type'])){
                switch($filter['type']){
                    case 5://全部
                        $where2 ['type'] = ['NEQ','not null'];
                        break;
                    default:
                    $where2 ['type'] = ['EQ',$filter['type']];
                    break;
                }
                unset($filter['type'],$op['type']);
            }
            $this->request->get(["filter"=>json_encode($filter),'op'=>json_encode($op)]);
        }

        
        //如果发送的来源是 Selectpage，则转发到 Selectpage
        if ($this->request->request('keyField')) {
            return $this->selectpage();
        }
        [$where, $sort, $order, $offset, $limit] = $this->buildparams();
        $list = $this->model
            ->where($where)
            ->where($where2)
            ->order($sort, $order)
            ->paginate($limit);
        $result = ['total' => $list->total(), 'rows' => $list->items()];
        return json($result);
    }

    //获取echart数据
    public function getEchartData(){
        $type = $this->request->post("type");
        $row_number = $this->request->post("row_number");
        if($type==2){
            $shelves = db('shelves')->where([
                'type' => $type,
                'row_number' => $row_number
            ])
            ->field('layers_number,column_number,number,ifempty')
            ->select();
        }else{
            $shelves = db('shelves')->where([
                'type' => $type
            ])
            ->field('number,ifempty')
            ->select();
        }
        

        $dataEmpty = [];
        $dataNumber = [];
        $xAxisArr = [];//横坐标
        $yAxisArr = [];//纵坐标
        $all_layers_number = 4;
        $shelves_type = [1=>'库区','货架','托盘'];
        $shelves_type_str = $shelves_type[$type];
        $shelves_name = $shelves_type_str.$row_number;

        if($shelves){
            $column_number = 1;
            $layers_number = 0;
            foreach($shelves as $k=>$shelve){
                if($type==2){//货架
                    if(!in_array("第{$shelve['column_number']}列",$xAxisArr)){
                        $xAxisArr[] = "第{$shelve['column_number']}列";
                    }
                    if(!in_array("第{$shelve['layers_number']}层",$yAxisArr)){
                        $yAxisArr[] = "第{$shelve['layers_number']}层";
                    }
                }else if($type==1||$type==3){
                    $layers_number++;
                    $shelve['column_number'] = $column_number;
                    $shelve['layers_number'] = $layers_number;
                    
                    if(!in_array($shelves_type_str.$column_number,$xAxisArr)){
                        $xAxisArr[] = $shelves_type_str.$column_number;
                    }
                    
                    if(!in_array($shelves_type_str.$layers_number,$yAxisArr)){
                        if($layers_number<=$all_layers_number){
                            $yAxisArr[] = $shelves_type_str.$layers_number;
                        }
                    }

                    if($k>0&&$k%4==0){
                        $column_number++;
                        $layers_number = 0;
                    }
                    
                }

                $dataEmpty[$shelve['column_number']][$shelve['layers_number']] = $shelve['ifempty']==1?0:1;
                $dataNumber[$shelve['column_number']][$shelve['layers_number']] = $shelve['number'];
            }
        }


        return json([$dataEmpty,$dataNumber,$xAxisArr,$yAxisArr,$shelves_name]);
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    //选择器界面

    public function choose()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if (false === $this->request->isAjax()) {
            return $this->view->fetch();
        }
        //如果发送的来源是 Selectpage，则转发到 Selectpage
        if ($this->request->request('keyField')) {
            return $this->selectpage();
        }
        [$where, $sort, $order, $offset, $limit] = $this->buildparams();
        $warehouse_id =$this->request->get('warehouse_id');
        $list = $this->model
            ->where($where)
            ->where('warehouse_id',$warehouse_id)
            ->order($sort, $order)
            ->paginate($limit);
        $result = ['total' => $list->total(), 'rows' => $list->items()];
        return json($result);
    }

    public function excel()
    {
       return $this->view->fetch();
    }



    public function getExcels()
    {
        header("content-type:text/html;charset=utf-8");

        $file = $this->request->file('file');

        if (empty($file)) {
            $this->error('请选择上传文件');
        }
        $info = $file->move(ROOT_PATH.'public'.DS.'upload');
        $filename = $info->getSaveName();

        $inputFileName = ROOT_PATH.'public'.DS.'upload'.DS.$filename;

        //处理Excel文档
        $spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load($inputFileName);
        $sheetsData = $spreadsheet->getAllSheets();
        $type = $this->request->get('type');
        $n=0;
        Db::startTrans();
        try{
            //遍历全部excel下标
            foreach ($sheetsData as $k=>$sheet) {
                $spreadsheet->setActiveSheetIndex($k);
                $sheetData = $spreadsheet->getActiveSheet();
                $highestRow = $sheet->getHighestRow(); // 总行数
                $highestColumn = $sheet->getHighestColumn(); // 总列数
                $highestColumnIndex = \PhpOffice\PhpSpreadsheet\Cell\Coordinate::columnIndexFromString($highestColumn); //列数
                if ($highestColumnIndex == 0) {
                    continue;
                }

//                $customVal="";
//                $cells =$sheetData->getMergeCells();
                //循环读取每个excel
                for ($row = 2; $row <= $highestRow; $row++) {
                    //$number = $sheetData->getCellByColumnAndRow(1, $row)->getValue();
                    $number = $sheetData->getCellByColumnAndRow(2, $row)->getValue();
                    if(!$number) continue;
                    $name = $sheetData->getCellByColumnAndRow(3, $row)->getValue();
                    $wareHouse = $sheetData->getCellByColumnAndRow(4, $row)->getValue();
                    $remark = $sheetData->getCellByColumnAndRow(5, $row)->getValue();
                    $address = $sheetData->getCellByColumnAndRow(6, $row)->getValue();
                    $status = $sheetData->getCellByColumnAndRow(7, $row)->getValue();
//                    //合并单元格处理
//                    foreach ($cells as $v){
//                        if ($custom && $sheetData->getCellByColumnAndRow(2, $row)->isInRange($v)) {$customVal = $custom;break;}
//                        else if(!$custom && $sheetData->getCellByColumnAndRow(2, $row)->isInRange($v)) {$custom = $customVal;break;}
//                    }
//                    unset($v);


                    // 时间字段处理
//                    $toTime =\PhpOffice\PhpSpreadsheet\Shared\Date::excelToTimestamp($date);
//                    $date = date('Y-m-d',$toTime);
                    $wareHouse_id = Db::name('warehouse')->where('name',$wareHouse)->value('id');
                    $list = Db::name('shelves')->where('number',$number)->find();
                    if(!empty($list)){
                        continue;
                    }
                    $insertData=[];
                    if($type==1){
                        $insertData=[
                            'warehouse_id'=>$wareHouse_id,
                            'type'=>$type,
                            'number'=>$number,
                            'name'=>$name,
                            'remark'=>$remark,
                            'switch'=>($status=="停用")?0:1,
                            'createtime'=>date('Y-m-d H:m:i',time())
                        ];
                    }else if($type==2){
                        preg_match_all("/\d+/",$name,$arr);
                        $insertData=[
                            'warehouse_id'=>$wareHouse_id,
                            'row_number'=>$arr[0][0],
                            'column_number'=>$arr[0][1],
                            'layers_number'=>$arr[0][2],
                            'type'=>$type,
                            'number'=>$number,
                            'name'=>$name,
                            'remark'=>$remark,
                            'switch'=>($status=="停用")?0:1,
                            'createtime'=>date('Y-m-d H:m:i',time())
                        ];
                    }
                    $insertData =$this->getCode($insertData);
                    Db::name('shelves')->insert($insertData);
                    $n++;
                }

            }
            Db::commit();
            return json(['msg'=>'导入成功,新增'.$n.'条数据']);
        }catch (Exception $e){
            Db::rollback();
            $this->error($e->getMessage().'数据行数'.($n==0?2:$n));
        }

    }

    /**
     * 获取编码规则
     *
     */
    public function getCode($data)
    {
        $first = db('warehouse')->where('id',$data['warehouse_id'])->value('number');
        if($data['type']==1){
            $id = db('shelves')->where(['type'=>1,'warehouse_id'=>$data['warehouse_id']])->count();
            $code = $first.'A'.$this->isAddZero($id+1);
        }else{
            $code = $first.'B'.$this->isAddZero($data['row_number']).$this->isAddZero($data['column_number']).$this->isAddZero($data['layers_number']);
        }
        if($code!=$data['number']) throw new Exception("编码规则有误");
        $data['number']=$code;
        return $data;
    }


    /**
     * 判断是否需要加0
     * @param $num
     * @return int|null|string
     */

    public function isAddZero($num)
    {
        $re = null;
        $num = is_string($num)?intval($num):$num;
        if($num<10) $re = '0'.$num;
        else  $re =$num;
        return $re;
    }


    /**
     * 编辑
     *
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }
            
            if($params['wh_type']!=$row->wh_type){
                if($this->kcModel::checkKcByWhIDShID($row->warehouse_id,$ids)){
                    exception('该记录下存在库存，无法更改属性');
                }
            }
            if($params['switch']!=$row->switch){
                if($this->kcModel::checkKcByWhIDShID($row->warehouse_id,$ids)){
                    exception('该记录下存在库存，无法更改状态');
                }
            }
            
            $inv_class1_ids = $params['inv_class1_id'];
            $inv_class2_ids = $params['inv_class2_id'];
            $inv_class3_ids = $params['inv_class3_id'];
            $invClassModel = new InventoryClass();
            $inv_class_ids = '';
            if($inv_class3_ids){
                //有3级
                $inv_class_ids = $inv_class3_ids;
            }else {
                //有2级
                if($inv_class2_ids){
                    $inv_class_ids = $inv_class2_ids;
                }else{
                    if($inv_class1_ids){
                        //只有1级
                        $inv_class_ids = $inv_class1_ids;
                    }
                }
            }
            
            if($inv_class_ids){
                $inv_class_ids_arr = explode(',', $inv_class_ids);
                $inv_class_name_arr = db('inventory_class')->where(['id'=>['in',$inv_class_ids_arr]])->column('cInvCName');
                $params['inv_class_name'] = implode(',', $inv_class_name_arr);
                
                //先清除
                db('shelves_invclass')->where('shelves_id',$ids)->delete();
                
                //循环增加
                foreach ($inv_class_ids_arr as $inv_class_id){
                    $childIdsArr = $invClassModel->getChildIds($inv_class_id);
                    $invClassModel->addRelation($childIdsArr,$ids);
                }
            }else{
                //先清除
                db('shelves_invclass')->where('shelves_id',$ids)->delete();
                $params['inv_class_name'] = null;
            }
            
            $result = $row->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }

    /**
     * 删除
     *
     * @param $ids
     * @return void
     * @throws DbException
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     */
    public function del($ids = null)
    {
        if (false === $this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ?: $this->request->post("ids");
        if (empty($ids)) {
            $this->error(__('Parameter %s can not be empty', 'ids'));
        }
        $pk = $this->model->getPk();
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            $this->model->where($this->dataLimitField, 'in', $adminIds);
        }
        $list = $this->model->where($pk, 'in', $ids)->select();
        
        $count = 0;
        Db::startTrans();
        try {
            foreach ($list as $item) {
                if($this->kcModel::checkKcByWhIDShID($item->warehouse_id,$item->id)){
                    exception('该记录下存在库存，无法删除');
                }
                $count += $item->delete();
            }
            Db::commit();
        } catch (PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($count) {
            $this->success();
        }
        $this->error(__('No rows were deleted'));
    }
    
    public function getTreeData(){
        $warehouse_id = $this->request->request('warehouse_id');
        $data = $this->model->getTreeData($warehouse_id);
        $classtree = new Tree();
        $classtree->init($data);
        $treeList = $classtree->getTreeList($classtree->getTreeArray(0), 'name');

        foreach ($treeList as $k => $v) {
            $jsList[] = array(
                'id' => $v['id'],
                'parent' => $v['pid'] ? $v['pid'] : '#',
                'text' => __($v['name']),
            );
        }
        $this->success('','',$jsList);
    }
}
